import Vue from 'vue'
import VueRouter from 'vue-router'
import MainLayout from '../components/layout/MainLayout.vue'
import Login from '../views/Login.vue'

// 预加载常用组件
const DataEntry = () => import(/* webpackChunkName: "data-entry" */ '../views/DataEntry.vue')
const Display = () => import(/* webpackChunkName: "display" */ '../views/Display.vue')
const PersonalProfile = () => import(/* webpackChunkName: "personal-profile" */ '../views/PersonalProfile.vue')
const KeyPersonList = () => import(/* webpackChunkName: "key-person-list" */ '../views/KeyPersonList.vue')

// 预加载其他组件
const preloadComponents = () => {
  // 在空闲时间预加载其他组件
  setTimeout(() => {
    import(/* webpackChunkName: "health-category" */ '../views/HealthCategory.vue')
    import(/* webpackChunkName: "study-category" */ '../views/StudyCategory.vue')
    import(/* webpackChunkName: "life-category" */ '../views/LifeCategory.vue')
    import(/* webpackChunkName: "social-category" */ '../views/SocialCategory.vue')
    import(/* webpackChunkName: "thought-category" */ '../views/ThoughtCategory.vue')
    import(/* webpackChunkName: "unstructured-data-category" */ '../views/UnstructuredDataCategory.vue')
    import(/* webpackChunkName: "audio-data-category" */ '../views/AudioDataCategory.vue')
    import(/* webpackChunkName: "text-data-category" */ '../views/TextDataCategory.vue')
    import(/* webpackChunkName: "video-data-category" */ '../views/VideoDataCategory.vue')
  }, 3000)
}

// 在应用启动后预加载组件
if (typeof window !== 'undefined') {
  window.addEventListener('load', preloadComponents)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/home',
    component: MainLayout,
    meta: { requiresAuth: false },
    children: [
      {
        path: '',
        name: 'display',
        component: Display
      },
      {
        path: '/personal-profile',
        name: 'personal-profile',
        component: PersonalProfile
      },
      {
        path: '/student-detail/:id',
        name: 'student-detail',
        component: () => import('../views/StudentDetail.vue')
      },
      {
        path: '/key-person-list',
        name: 'key-person-list',
        component: KeyPersonList
      },
      // 健康类别
      {
        path: '/health-category',
        name: 'health-category',
        component: () => import('../views/HealthCategory.vue')
      },
      // 重定向直接访问的子模块到对应的类别页面
      {
        path: '/medical-situation',
        redirect: '/health-category'
      },
      {
        path: '/physical-exercise',
        redirect: '/health-category'
      },

      // 学习类别
      {
        path: '/study-category',
        name: 'study-category',
        component: () => import('../views/StudyCategory.vue')
      },
      {
        path: '/study-performance',
        redirect: '/study-category'
      },

      // 生活类别
      {
        path: '/life-category',
        name: 'life-category',
        component: () => import('../views/LifeCategory.vue')
      },
      {
        path: '/dormitory-management',
        redirect: '/life-category'
      },

      // 社交类别
      {
        path: '/social-category',
        name: 'social-category',
        component: () => import('../views/SocialCategory.vue')
      },

      // 作风养成类别
      {
        path: '/thought-category',
        name: 'thought-category',
        component: () => import('../views/ThoughtCategory.vue')
      },

      // 非结构化数据类别
      {
        path: '/unstructured-data',
        name: 'unstructured-data',
        component: () => import('../views/UnstructuredDataCategory.vue')
      },
      // 音频类数据
      {
        path: '/audio-data',
        name: 'audio-data',
        component: () => import('../views/AudioDataCategory.vue')
      },
      // 文本类数据
      {
        path: '/text-data',
        name: 'text-data',
        component: () => import('../views/TextDataCategory.vue')
      },
      // 文本筛选结果
      {
        path: '/text-data-results',
        name: 'text-data-results',
        component: () => import('../views/TextDataResults.vue')
      },
      // 视频类数据
      {
        path: '/video-data',
        name: 'video-data',
        component: () => import('../views/VideoDataCategory.vue')
      },

      // 量表分析模块
      {
        path: '/questionnaire-processing',
        name: 'questionnaire-processing',
        component: () => import('../views/QuestionnaireProcessing.vue')
      },
      {
        path: '/questionnaire-first',
        name: 'questionnaire-first',
        component: () => import('../views/QuestionnaireFirst.vue')
      },
      {
        path: '/questionnaire-detail/:name/:type',
        name: 'questionnaire-detail',
        component: () => import('../views/QuestionnaireDetail.vue')
      },

      // 其他模块
      {
        path: '/data-entry',
        name: 'data-entry',
        component: DataEntry
      },
      {
        path: '/system-settings',
        name: 'system-settings',
        component: () => import('../views/SystemSettings.vue')
      },

    ]
  }
]

const router = new VueRouter({
  routes
})

// 添加全局导航守卫
router.beforeEach((to, from, next) => {
  window.navStartTime = Date.now();
  // 新增：新生管理员权限控制
  try {
    const user = (window.localStorage && window.localStorage.getItem('vuex'))
      ? JSON.parse(JSON.parse(window.localStorage.getItem('vuex')).auth.currentUser || '{}')
      : null;
    if (user && (user.role === '5' || user.role === 5)) {
      // 只允许访问量表相关页面
      const allowList = [
        '/questionnaire-processing',
      ];
      // 允许访问量表详情页（带参数）
      if (allowList.includes(to.path) || to.path.startsWith('/questionnaire-detail')) {
        next();
      } else if (to.path === '/home' || to.path === '/' || to.path === '/home/display') {
        // 访问首页时自动跳转到量表处理页面
        next('/questionnaire-processing');
      } else {
        next('/questionnaire-processing');
      }
      return;
    }
  } catch (e) { /* 忽略异常 */ }
  next();
})

// 导航完成后的处理
router.afterEach(() => {
  // 计算导航耗时
  const navEndTime = Date.now()
  const navDuration = navEndTime - (window.navStartTime || navEndTime)
  console.log(`导航完成，耗时: ${navDuration}ms`)

  // 确保至少显示加载状态 300ms，避免闪烁
  const minLoadingTime = 300
  const remainingTime = Math.max(0, minLoadingTime - navDuration)

  setTimeout(() => {
    // 重置导航状态
    if (router.app.$root) {
      const mainLayout = router.app.$root.$children[0].$children.find(c => c.$options.name === 'MainLayout')
      if (mainLayout) {
        mainLayout.isNavigating = false
      }
    }
  }, remainingTime)
})

export default router
